package com.pattern.adapter.springmvc;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 冯志立
 * @create 2019-10-25 17:41
 */
public class DispatchServlet {
    public static List<HanderAdapter> handerAdapters = new ArrayList<HanderAdapter>();

    public DispatchServlet(){
        handerAdapters.add(new AnnotationHandlerAdapter());
        handerAdapters.add(new SimpleHandlerAdapter());
        handerAdapters.add(new HttpHandlerAdapter());
    }

    public void doDispatch(){
        //此处模拟SpringMVC从request去handler的对象，
        //适配器可以获取到希望的controller
        //HttpController controller = new HttpController();
        AnnotationController controller = new AnnotationController();
        //SimpleController controller = new SimpleController();
        //得到对应适配器
        HanderAdapter adapter = getHandler(controller);

        adapter.handle(controller);
    }

    public HanderAdapter getHandler(Controller controller) {
        //遍历：得到的controller返回对应的适配器
        for (HanderAdapter adapter: this.handerAdapters) {
            if (adapter.supports(controller)) {
                return adapter;
            }
        }
        return null;
    }

}
